package com.guigu.Curriculum.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.Curriculum.entity.AbCourse;
import com.guigu.Curriculum.entity.Vo.AbCourselecturer;
import com.guigu.Curriculum.entity.Vo.AbcourseVo;
import com.guigu.Curriculum.enums.CourseStatusEnum;
import com.guigu.Curriculum.mapper.AbCourseMapper;
import com.guigu.Curriculum.service.AbCourseService;
import com.guigu.Curriculum.utils.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author liulinjun
 * @since 2020-07-11
 */
@RestController
@RequestMapping("/abCourse")
public class AbCourseController {
    @Autowired
    private AbCourseService abCourseService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private AbCourseMapper abCourseMapper;
    //Test单点登陆
//    private static final String USER_KEY="user_key";
    //Redis接口
//    @Autowired
//    private StoreInterface redisStore;

    private  QueryWrapper queryWrapper=new QueryWrapper();
    //
    @RequestMapping(value = "/updStatus",method = RequestMethod.GET)
    public Boolean getabcourse(String courseId){
        AbCourse byId = abCourseService.getById(courseId);
        //System.out.println(byId+"++++++++++++++++++++++++");
        //System.out.println(CourseStatusEnum.Draft);
        //System.out.println(byId.getCourseStatus().equals(CourseStatusEnum.Draft));
        if(byId.getCourseStatus().equals(CourseStatusEnum.Draft)){
            //System.out.println("----------------------"+CourseStatusEnum.Normal);
            //
            AbCourse abCourse = byId.setCourseStatus(CourseStatusEnum.Normal);
            // System.out.println("+++++++++++++++++++"+abCourse.getCourseStatus());
        }else{
            byId.setCourseStatus(CourseStatusEnum.Draft);
        }
        boolean b = abCourseService.updateById(byId);

        //分页查询
//            Page<AbCourse> objectPage = new Page<>(1, 2);
//            IPage<AbCourse> page = abCourseService.page(objectPage);
//            System.out.println(page.getTotal());
//            page.getRecords().forEach(System.out::println);
        //System.out.println(abCourseService.getOne(queryWrapper));
        ;

        return  b;
    }
    //查询所有
    @RequestMapping(value = "selectall")
    public List<AbCourselecturer> getalls(@RequestParam(value = "id",required = false,defaultValue = "0") long id){
//        if(id!=0 || id>=0){
//            queryWrapper.eq("courseId",id);
//        }
        return  abCourseMapper.getoneTeacher(id);
    }


    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public boolean installcourse(@RequestBody AbCourse abCourse){
        System.out.println(111);
        if(abCourse!=null){

            boolean save = abCourseService.save(abCourse);
            return save;

        }
        return  false;
    }
    @RequestMapping(value = "/update",method = RequestMethod.PUT)
    public boolean updateabCourse(@RequestBody AbCourse abCourse){

        if(abCourse!=null){
            return abCourseService.updateById(abCourse);
        }
        return  false;
    }
    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    public int deleteabCourse(String courseId){
        System.out.println(courseId);
        if(courseId!=""){
            return  abCourseMapper.deleteById(courseId);
        }
        return 0;
    }
    // 数据放入elasticsearch
    @GetMapping(value = "/getinstall")
    public boolean getinstall() throws IOException {
        //把查询到的数据放入es中
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("2m");
        List<AbCourselecturer> list = abCourseMapper.getoneTeacher(1);

        for (AbCourselecturer abCourse :list) {
            System.out.println(abCourse);
            bulkRequest.add(
                    new IndexRequest("ab_curriculum")
                            .source(JSON.toJSONString(abCourse), XContentType.JSON)
            );
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulk.hasFailures();
    }
//    @GetMapping(value = "/getlecturer")
//    public Ab_lecturer getlecturer(){
//        Ab_lecturer body = this.restTemplate.getForEntity("http://Lecturer/findByidturer/1", Ab_lecturer.class).getBody();
//        body.getUserid();
//        return null;
//    }
    //3、获取这些数据实现搜索高亮功能
    @ResponseBody
    @RequestMapping(value = "selectalllecturer") //String keyword,int pageNo,int pagesize
    public List<Map<String,Object>> getlecturer(String keyword)throws IOException {

//            if(pageNo<1){
//                pageNo=1;
//            }
        System.out.println(keyword);
        //条件搜索
        SearchRequest searchRequest = new SearchRequest("ab_curriculum");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        // searchSourceBuilder.from(pageNo);
        //searchSourceBuilder.size(pagesize);

        //精准匹配
        TermQueryBuilder title = QueryBuilders.termQuery("courseTitle", keyword);

        searchSourceBuilder.query(title);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //高亮搜索
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("courseTitle");
        highlightBuilder.requireFieldMatch(false);//是否多个高亮显示
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);


        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        //解析结果
        ArrayList<Map<String,Object>> list=new ArrayList<>();
        for (SearchHit searchHit : search.getHits().getHits()) {
            Map<String, HighlightField> hit = searchHit.getHighlightFields();
            HighlightField title1 = hit.get("courseTitle");
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();  //原来的结果！
            //解析高亮的字段，将原来的字段换为我们高亮的字段即可！
            if(title1!=null){
                Text[] fragments = title1.fragments();
                String n_title = "";
                for (Text fragment : fragments) {
                    n_title += fragment;
                }
                sourceAsMap.put("courseTitle",n_title); // 高亮字段替换原来的内容即可！

            }
            //解析高亮字段
            list.add(sourceAsMap);
        }
        return list;

    }
//
//    //redis测试单点登陆
//    @RequestMapping("/getUser")
//    public  Object getUser(HttpServletRequest request, HttpServletResponse response){
//        Object user =request.getSession().getAttribute(USER_KEY);
//        Object o =redisStore.get(CookieUtil.getLoginCookie(request, response, false));
////        System.out.println( o.getUsername());
//        System.out.println(o);
//        return user+","+o+",";
//    }

}

